﻿/******************************
 * 1,新增数据库的操作
 * 2,对用户名和密码采用MD5加密技术
 * 3,完善登录和注册的逻辑判断
 *****************************/

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using AssemblyCSharp;
using System.Text;
using System.Security.Cryptography;
using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.IO;
using System.Xml;

public class Login : MonoBehaviour {

    public Toggle remPasswd;   //记住密码
    public Toggle forPasswd;   //忘记密码

    //登录信息
    public InputField account;
    public InputField password;

    public GameObject register;

    //注册信息
    public InputField reg_account;
    public InputField reg_password;
    public InputField reg_OKpassword; //确认密码

    //sql全局操作对象
    SqlAccess sql = new SqlAccess();

    void Awake()
    {
        password.inputType = InputField.InputType.Password;
        CreateXml();
        LoadXml();
        //regist = GameObject.Find("Canvas/Panel/regist") as GameObject;
    }

 

	void Start () {
        
        DataSet ds = sql.SelectAll("user");
        sql.ReadDs(ds);
	}

    /// <summary>
    /// 创建Xml
    /// </summary>
    private void CreateXml()
    {
        //xml保存的路径，这里放在Assets路径
        string filepath = Application.persistentDataPath + "/passwordData.xml";

        //判断当前路径下是否有该文件
        if (!File.Exists(filepath ))
        {
            //创建XMl实例，文档实例
            XmlDocument xmlDoc = new XmlDocument();
            //创建root节点，也就是最上一层节点
            XmlElement root = xmlDoc.CreateElement("root");
            //继续创建下一层节点
            XmlElement data_account = xmlDoc.CreateElement("account");
            //设置节点中的数值
            data_account.InnerText = "";
            XmlElement data_password = xmlDoc.CreateElement("password");
            data_account.InnerText = "";
            XmlElement data_save = xmlDoc.CreateElement("save");
            data_save.InnerText = "true";
            //把节点一层一层的添加至XMLDoc中
            root.AppendChild(data_account);
            root.AppendChild(data_password);
            root.AppendChild(data_save);
            xmlDoc.AppendChild(root);
            //把xml文件保存至本地
            xmlDoc.Save(filepath);
        }
    }

    /// <summary>
    /// 读Xml
    /// </summary>
    private void LoadXml()
    {
        string filepath = Application.persistentDataPath + "/passwordData.xml";


        if (File .Exists (filepath ))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("root").ChildNodes;

            foreach (XmlElement xl in nodeList)
            {
                if (xl.Name == "account")
                {
                    account.text = xl.InnerText;
                }

                if (xl.Name == "password")
                {
                    password.text = xl.InnerText;
                }
            }
            xmlDoc.Save(filepath);
        }
    }

    /// <summary>
    /// 登录事件
    /// </summary>
    public void OnClick()
    {
        //MD5加密
        byte[] result = Encoding.Default.GetBytes(password.text);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] output = md5.ComputeHash(result);
        Debug.Log("Md5:" + BitConverter.ToString(output));
        string Md5Passwd = BitConverter.ToString(output).Replace("-", "");
        Debug.Log(sql.ExistOrNot("select * from user where name = '" + account.text + "'" + "and passwd = '" + Md5Passwd + "'"));

        DataSet ds = sql.ExistOrNot("select * from user where name = '" + account.text + "'" + "and passwd ='" + Md5Passwd + "'");
        Debug.Log("检索到：" + ds.Tables[0].Rows.Count);

        //如果选中记住密码
        UpdateXml();

        if (ds.Tables[0].Rows .Count >0)
        {
            SceneManager.LoadScene("Loading");
        }else
        {
            //Debug.Log("登录失败");
            if (password .text == "" )
            {
                HintMessage.instance.Message("请输入密码!");
            }else
            {
                HintMessage.instance.Message("登录失败!");
            }          
        }
    }

    public void OnRegistClick()
    {
        register.SetActive(true);
        reg_account.text = "";
        reg_password.text = "";
        reg_OKpassword.text = "";
    }

    /// <summary>
    /// 关闭注册界面
    /// </summary>
    public void OnCloseRegistClick()
    {
        register.SetActive(false);
    }

    /// <summary>
    /// 注册事件
    /// </summary>
    public  void regist()
    {
        //如果可以的或直接将数据写入数据库在这里我们仅仅模拟下功能就行了
        if (reg_account .text != "" && reg_password .text != "")
        {
            //MD5加密
            byte[] result = Encoding.Default.GetBytes(reg_password .text);    //tbPass为输入密码的文本框  
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            Debug.Log("Md5:" + BitConverter.ToString(output));
            string Md5Passwd = BitConverter.ToString(output).Replace("-", ""); //tbMd5pass为输出加密文本的文本框 
                                                                               //			Debug.Log(Md5Passwd);
            Debug.Log(sql.ExistOrNot("select * from user where name = " + "'" + account .text + "'" + "and passwd = '" + Md5Passwd + "'"));
            DataSet ds = sql.ExistOrNot("select * from user where name = " + "'" + reg_account .text + "'" + "and passwd = '" + Md5Passwd + "'");
            //			Debug.Log ("检索到:"+ds.Tables[0].Rows.Count);
            if (ds.Tables[0].Rows.Count > 0)
            {
                //Debug.Log("该用户已存在,请重新输入!");
                HintMessage.instance.Message("该用户已存在,请重新输入!");
                return;
            }
            else if (reg_OKpassword.text == "")
            {
                HintMessage.instance.Message("请再次输入密码!");
                return;
            }
            else if (!Equals (reg_password.text,reg_OKpassword .text))
            {
                HintMessage.instance.Message("两次密码不一致!");
                return;
            }
            else
            {
                sql.InsertInto("user", new string[] { "name", "passwd" }, new string[] { reg_account .text, Md5Passwd });

                //关键值加密32位
                string keyStr = "11234567890123456789012345678901";
                HintMessage.instance.Message("注册成功!");
                //Debug.Log("注册成功");
                Encryption encrytion = new Encryption();
                string encryptionName = encrytion.encryptionContent(reg_account .text, keyStr);
                //				Debug.Log ("Name After Encryption:"+encryptionName);
                //				Debug.Log ("Name After DeEncryption:"+encrytion.decipheringContent(encryptionName,keyStr));

                string encryptionPasswd = encrytion.encryptionContent(reg_account .text, keyStr);
                //				Debug.Log ("Passwd After Encryption:"+encryptionPasswd);
                //				Debug.Log ("Passwd After DeEncryption:"+encrytion.decipheringContent(encryptionPasswd,keyStr));
                register.SetActive(false);
            }
        }
        else
        {
            HintMessage.instance.Message("请输入注册信息!");
            return;
        }
    }

    /// <summary>
    /// 更新Xml
    /// </summary>
    private void UpdateXml()
    {
        string filepath = Application.persistentDataPath + "/passwordData.xml";

        if (File.Exists(filepath))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("root").ChildNodes;

            if (remPasswd.isOn)
            {
                foreach (XmlElement xl in nodeList)
                {
                    if (xl.Name == "account")
                         xl.InnerText = account.text;
                    if (xl.Name == "password")
                         xl.InnerText = password.text;
                    if (xl.Name == "save")
                        xl.InnerText = "true";
                }
            }else
            {
                foreach (XmlElement xl in nodeList)
                {
                    if (xl.Name == "account")
                        xl.InnerText = account.text;
                    if (xl.Name == "password")
                        xl.InnerText = "";
                    if (xl.Name == "save")
                        xl.InnerText = "false";
                }
            }
            xmlDoc.Save(filepath);
        }
    }
}
